let enableMusic = true;
let enableSound = true;
let musicId = undefined;

const SAVE_DATA_KEY = 'AudioSettings';

function init() {
  let storageData = LocalData.getItem(SAVE_DATA_KEY, {
    enableMusic: true,
    enableSound: true,
  });
  enableMusic = storageData.enableMusic;
  enableSound = storageData.enableSound;
}

function save() {
  LocalData.setItem(SAVE_DATA_KEY, {
    enableMusic,
    enableSound,
  });
}

function playSound(filePath, volume, loop) {
  if (enableSound && filePath) {
    return cc.audioEngine.play(filePath, loop, volume);
  }
}

function stopSound(audioId) {
  if (enableSound && audioId) {
    return cc.audioEngine.stop(audioId);
  }
}

function setSoundVolume(audioId, volume) {
  if (enableSound && audioId) {
    return cc.audioEngine.setVolume(audioId, volume);
  }
}


let currentMusicPath = undefined;
let currentMusicVolume = undefined;

function playMusic(filePath, volume) {
  currentMusicPath = filePath;
  currentMusicVolume = volume;
  if (enableMusic) {
    if (musicId !== undefined) {
      stopMusic();
    }
    musicId = cc.audioEngine.play(filePath, true, volume);
    return musicId;
  }
}

function isMusicPlaying() {
  return (musicId !== undefined);
}

function stopMusic(clear) {
  if (musicId !== undefined) {
    cc.audioEngine.stop(musicId);
    musicId = undefined;
    if (clear === undefined) {
      clear = true;
    }
    if (clear) {
      currentMusicPath = undefined;
      currentMusicVolume = undefined;
    }
  }
}


function setSoundEnable(enable) {
  enableSound = enable;
  save();
}

function setMusicEnable(enable) {
  enableMusic = enable;
  if (!enable) {
    stopMusic(false);
  } else {
    if (currentMusicPath !== undefined) {
      playMusic(currentMusicPath, currentMusicVolume);
    }
  }
  save();
}

function resumeMusic() {
  if (currentMusicPath !== undefined) {
    playMusic(currentMusicPath, currentMusicVolume);
  }
}

function isSoundEnable() {
  return enableSound;
}

function isMusicEnable() {
  return enableMusic;
}

function pauseAll() {
  cc.audioEngine.pauseAll();
}

function resumeAll() {
  cc.audioEngine.resumeAll();
}

let AudioEngineWrapper = {
  init,
  playMusic,
  playSound,
  stopSound,
  setSoundVolume,
  stopMusic,
  resumeMusic,
  setMusicEnable,
  setSoundEnable,
  isSoundEnable,
  isMusicEnable,
  isMusicPlaying,
  pauseAll,
  resumeAll,
};

//全局变量
window.AudioEngineWrapper = window.AudioEngineWrapper || AudioEngineWrapper;

